/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.trandio.manager;

import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.trandio.util.Utiles;

/**
 *
 * @author root
 */
public class CargaPlanosServlet extends HttpServlet {
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
       
      
        MultipartRequest multipartRequest = new MultipartRequest(request, "/tmp/", /* 1MB */ 2048 * 2048, new DefaultFileRenamePolicy());

        String adjunto = "";
        if (multipartRequest.getFile("file") != null) {
            adjunto = multipartRequest.getFile("file").toString().substring(5, multipartRequest.getFile("file").toString().length());
        }

        int err = upload(request, response, multipartRequest, 123);
        
        
        File file = multipartRequest.getFile("file");
        
        //err = 3;
        
        out.println("{\"name\":\""+file.getName()+"\",\"errores\":\""+err+"\"}");
        
    }
    
    private int upload(HttpServletRequest request, HttpServletResponse response, MultipartRequest multipartRequest, int ticket) throws IOException {


        File tmpFile = multipartRequest.getFile("file");
        String ruta = "/opt/salus/"+"planos";
        File dir = new File(ruta);
        dir.mkdir();


        File dirToMove = new File(ruta);

        String newFileName = tmpFile.getName()/*+ tmpFile.getName().substring(tmpFile.getName().lastIndexOf('.'))*/;

        String archivo = tmpFile.getName();

        
        
        File fileToMove = new File(dirToMove, newFileName);
        tmpFile.renameTo(fileToMove);

         int numeroErrores=0;


        try {
                Utiles.unzip(ruta+"/"+newFileName);
        } catch (ZipException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                numeroErrores = 2;                
                
        } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
        }
        
        
        CargarPlanoPacientes cp = new CargarPlanoPacientes();
        
        
        File archivoErr = new File("/tmp/err_"+newFileName+"");
                archivoErr.delete();


                
        String nombreFile = newFileName.substring(0, newFileName.length()-4);        
                

           
        try {
            numeroErrores = cp.leePlanoPacientes(ruta+"/"+nombreFile+"/"+nombreFile, ";", nombreFile);
            
            if(numeroErrores>0){
               //out.println(numeroErrores);
                numeroErrores = 1;
            }else{
                cp.escribePlanoPacientes(ruta+"/"+nombreFile+"/"+nombreFile, ";");
            }
            
            
        } catch (Exception ex) {
            numeroErrores = 3;
            Logger.getLogger(CargaPlanosServlet.class.getName()).log(Level.SEVERE, null, ex);            
        }
            
        
        //numeroErrores: 1 = por estructura y contenido, 2 = no es zip, 3 = formato no valido 
        
        
        /**
         * Delete temporary file
         */
       // tmpFile.delete();

        /**
         * Display newly uploaded file
         */
        //response.sendRedirect(ruta+"/" + newFileName);
        return numeroErrores;
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
